#!/usr/bin/env python3
"""
Ford API使用示例脚本
基于fetchNgc2.json中记录的API端点信息
"""

import json
import requests
from urllib.parse import urlencode

def load_api_config():
    """从fetchNgc2.json加载API配置"""
    try:
        with open('fetchNgc2.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
        return config.get('api_endpoints', {})
    except Exception as e:
        print(f"❌ 加载配置失败: {e}")
        return {}

def build_api_url(api_config, model_name):
    """构建指定车型的API URL"""
    
    if 'vehicle_model' not in api_config or 'load' not in api_config['vehicle_model']:
        return None
    
    load_config = api_config['vehicle_model']['load']
    base_url = load_config['url']
    params = load_config['params'].copy()
    series_codes = load_config.get('series_codes', {})
    
    # 获取对应的series code
    series_code = series_codes.get(model_name)
    if not series_code:
        print(f"❌ 未找到 {model_name} 的series code")
        return None
    
    # 替换config参数中的series code
    config_template = params['config']
    params['config'] = config_template.replace('{SERIES_CODE}', series_code)
    
    # 构建完整URL
    full_url = f"{base_url}?{urlencode(params)}"
    return full_url

def extract_key_features_from_api_response(response_data, api_config):
    """从API响应中提取Key Features"""
    
    try:
        # 根据配置中的路径提取数据
        key_features_path = api_config['vehicle_model']['load']['key_features_path']
        # key_features_path = "data.keyFeatures.walkup.combined.features"
        
        # 按路径解析数据
        data = response_data
        for key in key_features_path.split('.'):
            data = data[key]
        
        # 提取特性描述
        features = []
        for feature in data:
            if 'descKf' in feature and feature['descKf']:
                features.append(feature['descKf'])
        
        return features
        
    except Exception as e:
        print(f"❌ 提取Key Features失败: {e}")
        return []

def demonstrate_api_usage():
    """演示API使用方法"""
    
    print("🔧 Ford API使用示例")
    print("=" * 50)
    
    # 加载配置
    api_config = load_api_config()
    if not api_config:
        print("❌ 无法加载API配置")
        return
    
    print("✅ API配置加载成功")
    print(f"📍 基础域名: {api_config.get('base_domain', 'N/A')}")
    print(f"📅 发现日期: {api_config.get('discovered_date', 'N/A')}")
    print(f"✅ 验证状态: {api_config.get('validation_status', 'N/A')}")
    
    # 展示支持的车型
    series_codes = api_config.get('vehicle_model', {}).get('load', {}).get('series_codes', {})
    print(f"\n🚗 支持的车型 ({len(series_codes)} 个):")
    for model, code in series_codes.items():
        print(f"  - {model}: {code}")
    
    # 构建示例URL
    test_model = "Titanium"
    api_url = build_api_url(api_config, test_model)
    
    if api_url:
        print(f"\n🔗 {test_model} 的API URL:")
        print(f"  {api_url}")
        
        print(f"\n📋 Key Features提取路径:")
        key_features_path = api_config['vehicle_model']['load']['key_features_path']
        print(f"  {key_features_path}")
        
        print(f"\n💡 使用说明:")
        usage_notes = api_config.get('usage_notes', {})
        for note_key, note_value in usage_notes.items():
            print(f"  • {note_key}: {note_value}")
    
    # 展示逆向工程结果摘要
    try:
        with open('fetchNgc2.json', 'r', encoding='utf-8') as f:
            full_config = json.load(f)
        re_results = full_config.get('reverse_engineering_results', {})
    except:
        re_results = {}
        
    if re_results:
        print(f"\n📊 逆向工程结果摘要:")
        
        feature_counts = re_results.get('feature_counts', {})
        print(f"  特性数量对比:")
        for model, count in feature_counts.items():
            print(f"    - {model}: {count} 个完整特性")
        
        problem_analysis = re_results.get('problem_analysis', {})
        if problem_analysis:
            print(f"  问题分析:")
            print(f"    - UI限制: {problem_analysis.get('ui_limitation', 'N/A')}")
            print(f"    - 原始提取: {problem_analysis.get('original_extraction', 'N/A')}")
            print(f"    - API提取: {problem_analysis.get('api_extraction', 'N/A')}")

def validate_config_structure():
    """验证配置文件结构的完整性"""
    
    print("\n🔍 验证配置文件结构...")
    
    # 加载完整配置（不仅仅是api_endpoints）
    try:
        with open('fetchNgc2.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
    except Exception as e:
        print(f"❌ 加载配置失败: {e}")
        return False
    
    api_config = config.get('api_endpoints', {})
    
    required_keys = [
        ('api_endpoints', ['vehicle_model']),
        ('api_endpoints', ['vehicle_model', 'load']),
        ('api_endpoints', ['vehicle_model', 'load', 'url']),
        ('api_endpoints', ['vehicle_model', 'load', 'params']),
        ('api_endpoints', ['vehicle_model', 'load', 'series_codes']),
        ('api_endpoints', ['vehicle_model', 'load', 'key_features_path']),
        ('api_endpoints', ['usage_notes']),
        ('root', ['reverse_engineering_results'])
    ]
    
    missing_keys = []
    for section, key_path in required_keys:
        if section == 'api_endpoints':
            data = api_config
        else:  # root
            data = config
            
        try:
            for key in key_path:
                data = data[key]
        except (KeyError, TypeError):
            missing_keys.append(f"{section}.{'.'.join(key_path)}")
    
    if missing_keys:
        print(f"❌ 缺少必要的配置项:")
        for key in missing_keys:
            print(f"  - {key}")
        return False
    else:
        print("✅ 配置文件结构完整")
        return True

if __name__ == "__main__":
    # 运行演示
    demonstrate_api_usage()
    
    # 验证配置结构
    validate_config_structure()
    
    print("\n🎉 API端点信息已成功记录到fetchNgc2.json中！")
    print("📚 未来可以使用这些信息来：")
    print("  1. 直接调用Ford API获取完整数据")
    print("  2. 扩展支持更多车型")
    print("  3. 优化数据提取策略")
    print("  4. 维护API端点的版本变更")
